import React, { useRef, useEffect } from 'react';
import { Card, CardContent } from './ui/card';
import { Skeleton } from './ui/skeleton';
import { Badge } from './ui/badge';
import { Compass, Ruler, CheckCircle, XCircle, Loader2, AlertTriangle } from 'lucide-react';
import { Alert, AlertDescription, AlertTitle } from './ui/alert';

interface DetectionResult {
  detected: boolean;
  confidence?: number;
  direction?: string;
  distance?: string;
  boundingBox?: {
    x: number;
    y: number;
    width: number;
    height: number;
  };
  message?: string;
  processTime?: number;
  angle?: number;
  depth_estimate?: number;
}

interface ResultDisplayProps {
  result: DetectionResult | null;
  isProcessing: boolean;
  targetObject: string;
  previewUrl: string | null;
  mediaType: 'image' | 'video' | null;
  error: string | null;
}

const ResultDisplay: React.FC<ResultDisplayProps> = ({
  result,
  isProcessing,
  targetObject,
  previewUrl,
  mediaType,
  error
}) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const mediaRef = useRef<HTMLImageElement | HTMLVideoElement>(null);

  // 绘制边界框
  useEffect(() => {
    if (!result?.detected || !result.boundingBox || !previewUrl || !canvasRef.current) {
      return;
    }

    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    const media = mediaRef.current;
    if (!media) return;

    // 确保canvas尺寸与媒体元素一致
    canvas.width = media.clientWidth;
    canvas.height = media.clientHeight;

    // 清除画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 绘制边界框
    const { x, y, width, height } = result.boundingBox;
    const boxX = x * canvas.width;
    const boxY = y * canvas.height;
    const boxWidth = width * canvas.width;
    const boxHeight = height * canvas.height;

    // 设置边界框样式
    ctx.strokeStyle = '#ff8f00'; // 橙色
    ctx.lineWidth = 3;
    ctx.strokeRect(boxX, boxY, boxWidth, boxHeight);

    // 添加标签
    ctx.fillStyle = '#ff8f00';
    ctx.fillRect(boxX, boxY - 25, targetObject.length * 15 + 40, 25);
    ctx.fillStyle = 'white';
    ctx.font = '16px Arial';
    ctx.fillText(`${targetObject} ${Math.round((result.confidence || 0) * 100)}%`, boxX + 5, boxY - 7);
  }, [result, previewUrl, targetObject]);

  // 获取距离文本描述
  const getDistanceText = (distance?: string) => {
    if (!distance) return '未知';
    switch (distance) {
      case 'near': return '近距离';
      case 'medium': return '中等距离';
      case 'far': return '远距离';
      default: return distance; // 如果后端直接返回中文描述
    }
  };

  // 渲染错误状态
  if (error) {
    return (
      <Alert variant="destructive" className="mb-6">
        <AlertTriangle className="h-4 w-4" />
        <AlertTitle>识别失败</AlertTitle>
        <AlertDescription>
          {error}
        </AlertDescription>
      </Alert>
    );
  }

  // 渲染加载状态
  if (isProcessing) {
    return (
      <div className="flex flex-col items-center justify-center p-8">
        <Loader2 className="h-12 w-12 text-primary animate-spin mb-4" />
        <p className="text-lg font-medium">正在识别中，请稍候...</p>
        <p className="text-sm text-gray-500 mt-2">正在分析{mediaType === 'image' ? '图片' : '视频'}中的目标物体</p>
      </div>
    );
  }

  // 渲染无结果状态
  if (!result && !isProcessing) {
    return (
      <div className="text-center p-8">
        <p className="text-lg font-medium">请上传媒体文件并输入目标物体后开始识别</p>
        {previewUrl && (
          <div className="mt-4 rounded-lg overflow-hidden border border-gray-200">
            {mediaType === 'image' ? (
              <img 
                src={previewUrl} 
                alt="预览图片" 
                className="w-full h-auto max-h-[300px] object-contain"
              />
            ) : (
              <video 
                src={previewUrl} 
                controls 
                className="w-full h-auto max-h-[300px]"
              />
            )}
          </div>
        )}
      </div>
    );
  }

  return (
    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
      {/* 媒体显示区域 */}
      <div className="relative rounded-lg overflow-hidden border border-gray-200 bg-black/5">
        {mediaType === 'image' ? (
          <img 
            ref={mediaRef as React.RefObject<HTMLImageElement>}
            src={previewUrl || ''} 
            alt="识别结果" 
            className="w-full h-auto max-h-[400px] object-contain"
          />
        ) : (
          <video 
            ref={mediaRef as React.RefObject<HTMLVideoElement>}
            src={previewUrl || ''} 
            controls 
            className="w-full h-auto max-h-[400px]"
          />
        )}
        
        {/* 边界框叠加层 */}
        {result?.detected && (
          <canvas 
            ref={canvasRef}
            className="absolute top-0 left-0 w-full h-full pointer-events-none"
          />
        )}
      </div>

      {/* 识别结果面板 */}
      <div className="space-y-4">
        <Card className={`border-l-4 ${result?.detected ? 'border-l-green-500' : 'border-l-red-500'}`}>
          <CardContent className="p-6">
            <div className="flex items-center mb-4">
              {result?.detected ? (
                <CheckCircle className="h-8 w-8 text-green-500 mr-3" />
              ) : (
                <XCircle className="h-8 w-8 text-red-500 mr-3" />
              )}
              <div>
                <h3 className="text-xl font-medium">
                  {result?.detected ? '已检测到目标物体' : '未检测到目标物体'}
                </h3>
                <p className="text-sm text-gray-500">
                  {result?.message || (result?.detected 
                    ? `已在${mediaType === 'image' ? '图片' : '视频'}中找到${targetObject}`
                    : `在${mediaType === 'image' ? '图片' : '视频'}中未找到${targetObject}，请尝试转换视角`
                  )}
                </p>
              </div>
            </div>

            {result?.detected && (
              <>
                <div className="grid grid-cols-2 gap-4 mb-4">
                  <div className="flex items-center">
                    <Badge variant="outline" className="mr-2">置信度</Badge>
                    <div className="w-full bg-gray-200 rounded-full h-2.5">
                      <div 
                        className="bg-accent h-2.5 rounded-full" 
                        style={{ width: `${Math.round((result.confidence || 0) * 100)}%` }}
                      ></div>
                    </div>
                    <span className="ml-2 text-sm font-medium">
                      {Math.round((result.confidence || 0) * 100)}%
                    </span>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <Card className="p-4">
                    <div className="flex items-center mb-2">
                      <Compass className="h-5 w-5 text-primary mr-2" />
                      <h4 className="font-medium">方位</h4>
                    </div>
                    <p className="text-lg">{result.direction || '未知'}</p>
                  </Card>

                  <Card className="p-4">
                    <div className="flex items-center mb-2">
                      <Ruler className="h-5 w-5 text-primary mr-2" />
                      <h4 className="font-medium">距离</h4>
                    </div>
                    <p className="text-lg">{getDistanceText(result.distance)}</p>
                  </Card>
                </div>

                {result.processTime && (
                  <div className="mt-4 text-sm text-gray-500">
                    处理时间: {result.processTime.toFixed(2)}秒
                  </div>
                )}
              </>
            )}
          </CardContent>
        </Card>

        {!result?.detected && (
          <div className="p-4 bg-yellow-50 rounded-lg border border-yellow-100">
            <h3 className="text-sm font-medium text-yellow-800 mb-2">提示</h3>
            <p className="text-sm text-yellow-700">
              未检测到目标物体，请尝试以下操作：
              <ul className="list-disc list-inside mt-2">
                <li>转换拍摄角度</li>
                <li>调整光线条件</li>
                <li>确保目标物体在画面中</li>
                <li>尝试使用不同的目标物体名称</li>
              </ul>
            </p>
          </div>
        )}
      </div>
    </div>
  );
};

export default ResultDisplay;